/**
 * 添加提醒
 */
package com.niannian.activity;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
import com.niannian.adapter.NumericWheelAdapter;
import com.niannian.adapter.OnWheelScrollListener;
import com.niannian.bean.RegardsTipBean;
import com.niannian.util.AsyncHandle;
import com.niannian.util.Common;
import com.niannian.util.ErrorCode;
import com.niannian.util.MyTextWatcher;
import com.niannian.util.Sys;
import com.niannian.util.UmengPage;
import com.niannian.view.WheelView;
import com.niannian.web.nnSyncApi;
import com.niannian.BaseActivity;
import com.niannian.R;
import com.umeng.analytics.MobclickAgent;

/**
 * 添加提醒
 * 
 * @author shengl
 * 
 */
public class AddDateTipActivity extends BaseActivity {
	private EditText et_date_tip_title, et_remark;
	private TextView tv_date_tip, tv_setting, tv_time;
	private Button btn_tip_submit;
	LinearLayout ll_add_date_tip, ll_remark;
	int tid = 0;
	String title = "";
	int settingString = 0;
	String desc = "";
	public static AddDateTipActivity instance;
	RegardsTipBean regardsTipBean;

	int from = 0;// 1.来自编辑，2来自查看详情

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_push_regards_tip);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		try {
			from = getIntent().getIntExtra("from", 0);
			regardsTipBean = (RegardsTipBean) getIntent().getExtras().get("fdata");
		} catch (Exception e) {
			// TODO: handle exception
		}
		initView();
		setLister();
		initData();
		initTopView();
		instance = this;
	}

	// 头部视图
	private ImageView iv_top_left, iv_top_right;
	private TextView top_title, tv_top_right;
	private LinearLayout iv_top_left2, top_title2;

	private void initTopView() {
		iv_top_left = (ImageView) findViewById(R.id.iv_top_left);
		iv_top_left2 = (LinearLayout) findViewById(R.id.iv_top_left2);
		iv_top_left.setVisibility(View.VISIBLE);
		iv_top_left2.setVisibility(View.GONE);

		top_title = (TextView) findViewById(R.id.top_title);
		top_title2 = (LinearLayout) findViewById(R.id.top_title2);
		top_title.setVisibility(View.VISIBLE);
		top_title2.setVisibility(View.GONE);

		iv_top_right = (ImageView) findViewById(R.id.iv_top_right);
		iv_top_right.setVisibility(View.GONE);
		tv_top_right = (TextView) findViewById(R.id.tv_top_right);
		tv_top_right.setVisibility(View.VISIBLE);
		iv_top_left.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myfinish();
			}
		});

		if (from == 0) {
			top_title.setText("添加提醒");
			iv_top_right.setImageResource(R.drawable.add_confirm_e);
			iv_top_right.setEnabled(false);

			tv_top_right.setText("完成");
			// tv_top_right.setEnabled(false);
			viewEnabled(true);
		} else if (from == 1) {
			top_title.setText("编辑提醒");
			iv_top_right.setImageResource(R.drawable.add_confirm);
			iv_top_right.setEnabled(true);
			tv_top_right.setText("编辑");
			// tv_top_right.setEnabled(true);
			viewEnabled(true);
		} else if (from == 2) {
			top_title.setText("提醒详情");
			iv_top_right.setImageResource(R.drawable.edit);
			iv_top_right.setEnabled(true);
			tv_top_right.setText("编辑");
			// tv_top_right.setEnabled(true);
			viewEnabled(false);
		}
		tv_top_right.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				if (from == 0 || from == 1) {
					hideSoftInputFromWindow();
					title = et_date_tip_title.getText().toString();
					if (Common.empty(title)) {
						Common.tip(AddDateTipActivity.this, "请填写事件名称");
						return;
					}

					if (Common.empty(tv_date_tip.getText().toString())) {
						Common.tip(AddDateTipActivity.this, "请填写事件日期");
						return;
					}
					desc = et_remark.getText().toString().trim();
					new PostSubmit().init(AddDateTipActivity.this, null, true, "提交中...").execute();
				} else if (from == 2) {
					from = 1;
					top_title.setText("编辑提醒");
					iv_top_right.setImageResource(R.drawable.add_confirm);
					tv_top_right.setText("完成");
					et_remark.setText(regardsTipBean.getDesc());
					ll_remark.setVisibility(View.VISIBLE);
					viewEnabled(true);

					final Animation animation = (Animation) AnimationUtils.loadAnimation(ll_add_date_tip.getContext(), R.anim.item_anim);
					animation.setAnimationListener(new AnimationListener() {
						public void onAnimationStart(Animation animation) {
						}

						public void onAnimationRepeat(Animation animation) {
						}

						public void onAnimationEnd(Animation animation) {

						}
					});

					ll_add_date_tip.startAnimation(animation);

				}
			}
		});
		et_date_tip_title.addTextChangedListener(textWatcher);
		tv_date_tip.addTextChangedListener(textWatcher);
		tv_time.addTextChangedListener(textWatcher);
	}

	private void viewEnabled(Boolean isBoolean) {
		et_date_tip_title.setEnabled(isBoolean);
		tv_date_tip.setEnabled(isBoolean);
		tv_time.setEnabled(isBoolean);
		et_remark.setEnabled(isBoolean);
		tv_setting.setEnabled(isBoolean);
	}

	private MyTextWatcher textWatcher = new MyTextWatcher() {
		@Override
		public void onFocusChange(View view, boolean hasFocus) {
		};

		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			title = et_date_tip_title.getText().toString().trim();

			if (!Common.empty(title) && !Common.empty(tv_date_tip.getText().toString().trim()) && !Common.empty(tv_time.getText().toString().trim())) {
				// tv_top_right.setEnabled(true);

				if (from == 0 || from == 1) {
					iv_top_right.setImageResource(R.drawable.add_confirm);
					// tv_top_right.setText("完成");
				}
			} else {
				// iv_top_right.setEnabled(false);
				// tv_top_right.setEnabled(false);
				if (from == 0 || from == 1) {
					iv_top_right.setImageResource(R.drawable.add_confirm_e);
					tv_top_right.setText("完成");
				}
			}
		}
	};

	private void initView() {
		et_date_tip_title = (EditText) findViewById(R.id.et_date_tip_title);
		tv_date_tip = (TextView) findViewById(R.id.tv_date_tip);
		tv_setting = (TextView) findViewById(R.id.tv_setting);
		tv_time = (TextView) findViewById(R.id.tv_time);
		et_remark = (EditText) findViewById(R.id.et_remark);

		tv_setting.setText("当天提醒");

		btn_tip_submit = (Button) findViewById(R.id.btn_tip_submit);
		btn_tip_submit.setVisibility(View.GONE);

		ll_add_date_tip = (LinearLayout) findViewById(R.id.ll_add_date_tip);
		ll_remark = (LinearLayout) findViewById(R.id.ll_remark);
	}

	private void initData() {
		try {
			if (from == 1 || from == 2) {
				if (!Common.empty(regardsTipBean)) {
					tid = regardsTipBean.getId();

					et_date_tip_title.setText(regardsTipBean.getTitle());
					String dateString = Common.sgmdate2(regardsTipBean.getSpec_date());

					cDate = dateString.split(" ")[0];
					tv_date_tip.setText(cDate);

					cTime = dateString.split(" ")[1].substring(0, 5);
					tv_time.setText(cTime);

					String setting = "当天提醒";
					settingString = regardsTipBean.getNotice_type();
					if (settingString == 0) {
						setting = "当天提醒";
					} else if (settingString == 30) {
						setting = "提前一个月提醒";
					} else {
						setting = "提前" + regardsTipBean.getNotice_type() + "天提醒";
					}
					tv_setting.setText(setting);

					if (from == 1) {
						ll_remark.setVisibility(View.VISIBLE);
						et_remark.setText(regardsTipBean.getDesc());
					} else {
						et_remark.setText(regardsTipBean.getDesc() + " ");
						if (regardsTipBean.getDesc().length() > 0) {
							ll_remark.setVisibility(View.VISIBLE);
							et_remark.setText(regardsTipBean.getDesc());
						} else {
							ll_remark.setVisibility(View.GONE);

						}
					}
				}
			}

		} catch (Exception e) {

		}
	}

	private void setLister() {
		tv_date_tip.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				hideSoftInputFromWindow();
				chooseDate();
			}
		});

		btn_tip_submit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				hideSoftInputFromWindow();
				title = et_date_tip_title.getText().toString();
				desc = et_remark.getText().toString();
				new PostSubmit().init(AddDateTipActivity.this, null, true, "提交中...").execute();
			}
		});
		tv_setting.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				hideSoftInputFromWindow();
				initPopuwindow1();
			}
		});
		tv_time.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				hideSoftInputFromWindow();
				chooseTime();
			}
		});
	}

	View chooseDate;
	private int year_start = 2014;
	private PopupWindow popupDate;
	String cDate = "";

	private void chooseDate() {
		cDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis()));
		// TODO Auto-generated method stub
		chooseDate = LayoutInflater.from(instance).inflate(R.layout.year_month_day, null);
		TextView title = (TextView) chooseDate.findViewById(R.id.wheel_title);
		final WheelView year = (WheelView) chooseDate.findViewById(R.id.wheel_year);
		final WheelView month = (WheelView) chooseDate.findViewById(R.id.wheel_month);
		final WheelView day = (WheelView) chooseDate.findViewById(R.id.wheel_day);

		title.setText("选择提醒日期");

		if (!Common.empty(tv_date_tip.getText().toString().trim())) {
			cDate = tv_date_tip.getText().toString().trim();
		}
		// String tm = tv_greeting_date_1.getText().toString();
		/*
		 * if (TextUtils.isEmpty(tm)) { tm = "1990/1/1"; }
		 */

		Calendar old = Sys.StringToDate(cDate, "yyyy-MM-dd");
		int tmp_year = old.get(Calendar.YEAR);
		final int tmp_month = old.get(Calendar.MONTH) + 1;
		int tmp_day = old.get(Calendar.DAY_OF_MONTH);

		Calendar c = Calendar.getInstance();
		year_start = c.get(Calendar.YEAR);
		year.setAdapter(new NumericWheelAdapter(year_start, year_start + 4, "%02d", "年"));
		year.setCyclic(true);
		year.setCurrentItem(tmp_year - year_start);

		month.setAdapter(new NumericWheelAdapter(1, 12, "%02d", "月"));
		month.setCyclic(true);
		month.setCurrentItem(tmp_month - 1);

		day.setAdapter(new NumericWheelAdapter(1, c.getActualMaximum(Calendar.DAY_OF_MONTH), "%02d", "日"));
		day.setCyclic(true);
		day.setCurrentItem(tmp_day - 1);

		year.addScrollingListener(new OnWheelScrollListener() {

			@Override
			public void onScrollingStarted(WheelView wheel) {
			}

			@Override
			public void onScrollingFinished(WheelView wheel) {
				Calendar tmp = Calendar.getInstance();
				int _year_index = year.getCurrentItem();
				int _month_index = month.getCurrentItem();
				tmp.set(Calendar.YEAR, _year_index + year_start);
				tmp.set(Calendar.MONTH, _month_index);
				int _max_day_of_month = tmp.getActualMaximum(Calendar.DAY_OF_MONTH);
				day.setAdapter(new NumericWheelAdapter(1, _max_day_of_month, "%02d", "日"));

				if (day.getCurrentItem() > _max_day_of_month - 1) {
					day.setCurrentItem(0);
				}

			}
		});

		month.addScrollingListener(new OnWheelScrollListener() {

			@Override
			public void onScrollingStarted(WheelView wheel) {
			}

			@Override
			public void onScrollingFinished(WheelView wheel) {
				Calendar tmp = Calendar.getInstance();
				int _year_index = year.getCurrentItem();
				int _month_index = month.getCurrentItem();
				tmp.set(Calendar.YEAR, _year_index + year_start);
				tmp.set(Calendar.MONTH, _month_index);
				int _max_day_of_month = tmp.getActualMaximum(Calendar.DAY_OF_MONTH);
				day.setAdapter(new NumericWheelAdapter(1, _max_day_of_month, "%02d", "日"));

				if (day.getCurrentItem() > _max_day_of_month - 1) {
					day.setCurrentItem(0);
				}
			}
		});

		Button btn_ok = (Button) chooseDate.findViewById(R.id.btn_ok);
		btn_ok.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				int nYear = year.getCurrentItem() + year_start;
				int nMonth = month.getCurrentItem() + 1;

				int nDay = day.getCurrentItem() + 1;
				cDate = String.format("%02d-%02d-%02d", nYear, nMonth, nDay);
				// tv_date_tip.setText(String.format("%02d", nMonth) + "月" +
				// String.format("%02d", nDay) + "号");
				tv_date_tip.setText(cDate);
				popupDate.dismiss();
			}
		});

		Button btn_cancel = (Button) chooseDate.findViewById(R.id.btn_cancel);
		btn_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				popupDate.dismiss();
			}
		});

		popupDate = new PopupWindow(chooseDate, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		popupDate.setBackgroundDrawable(new BitmapDrawable());
		popupDate.setAnimationStyle(R.style.ModePopupAnimation);
		popupDate.setOutsideTouchable(true);
		popupDate.setFocusable(true);

		popupDate.showAtLocation(tv_date_tip, Gravity.CENTER, 0, 0);

	}

	View chooseTime;
	private PopupWindow popupTime;
	String cTime = "";

	private void chooseTime() {
		// cTime = MyDate.getDateHM();
		cTime = "09:00";
		// TODO Auto-generated method stub
		chooseTime = LayoutInflater.from(instance).inflate(R.layout.time_layout, null);
		TextView title = (TextView) chooseTime.findViewById(R.id.time_wheel_title);
		final WheelView hour = (WheelView) chooseTime.findViewById(R.id.wheel_hour);
		final WheelView minute = (WheelView) chooseTime.findViewById(R.id.wheel_minute);

		title.setText("选择时间");

		if (!Common.empty(tv_time.getText().toString().trim())) {
			cTime = tv_time.getText().toString().trim();
		}

		int tmp_hour = Integer.parseInt(cTime.split(":")[0]);
		int tmp_minute = Integer.parseInt(cTime.split(":")[1]);

		hour.setAdapter(new NumericWheelAdapter(0, 23, "%02d", "时"));
		hour.setCyclic(true);
		hour.setCurrentItem(tmp_hour);

		minute.setAdapter(new NumericWheelAdapter(0, 59, "%02d", "分"));
		minute.setCyclic(true);
		minute.setCurrentItem(tmp_minute);

		Button btn_ok = (Button) chooseTime.findViewById(R.id.btn_ok);
		btn_ok.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				int nHour = hour.getCurrentItem();
				int nMinute = minute.getCurrentItem();
				cTime = String.format("%02d:%02d", nHour, nMinute);
				tv_time.setText(cTime);
				popupTime.dismiss();
			}
		});

		Button btn_cancel = (Button) chooseTime.findViewById(R.id.btn_cancel);
		btn_cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				popupTime.dismiss();
			}
		});

		popupTime = new PopupWindow(chooseTime, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		popupTime.setBackgroundDrawable(new BitmapDrawable());
		popupTime.setAnimationStyle(R.style.ModePopupAnimation);
		popupTime.setOutsideTouchable(true);
		popupTime.setFocusable(true);

		popupTime.showAtLocation(tv_time, Gravity.CENTER, 0, 0);

	}

	PopupWindow PopupWindow1;

	@SuppressWarnings("deprecation")
	private void initPopuwindow1() {
		View mMenuView = null;

		if (PopupWindow1 == null) {
			mMenuView = LayoutInflater.from(instance).inflate(R.layout.popupwindow_tip, null);

			final TextView tv_date1_1 = (TextView) mMenuView.findViewById(R.id.tv_date1_1);
			final TextView tv_date1_2 = (TextView) mMenuView.findViewById(R.id.tv_date1_2);
			final TextView tv_date1_3 = (TextView) mMenuView.findViewById(R.id.tv_date1_3);
			final TextView tv_date1_4 = (TextView) mMenuView.findViewById(R.id.tv_date1_4);
			final TextView tv_date1_5 = (TextView) mMenuView.findViewById(R.id.tv_date1_5);

			tv_date1_1.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					settingString = 0;
					tv_setting.setText(tv_date1_1.getText());
					PopupWindow1.dismiss();
				}
			});
			tv_date1_2.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					settingString = 1;
					tv_setting.setText(tv_date1_2.getText());
					PopupWindow1.dismiss();
				}
			});
			tv_date1_3.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					settingString = 3;
					tv_setting.setText(tv_date1_3.getText());
					PopupWindow1.dismiss();
				}
			});
			tv_date1_4.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					settingString = 7;
					tv_setting.setText(tv_date1_4.getText());
					PopupWindow1.dismiss();
				}
			});
			tv_date1_5.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					settingString = 30;
					tv_setting.setText(tv_date1_5.getText());
					PopupWindow1.dismiss();
				}
			});

			PopupWindow1 = new PopupWindow(mMenuView, mScreenWidth / 2, LayoutParams.WRAP_CONTENT, true);
			PopupWindow1.setBackgroundDrawable(new BitmapDrawable());
			PopupWindow1.setOutsideTouchable(true);
			PopupWindow1.setAnimationStyle(R.style.Popup_Animation_DownScale);
		} else {
			mMenuView = PopupWindow1.getContentView();
		}

		PopupWindow1.showAsDropDown(tv_setting, -0, -0);

	}

	private void hideSoftInputFromWindow() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(et_date_tip_title.getWindowToken(), 0); // 强制隐藏键盘
	}

	protected class PostSubmit extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {
			Common.tip(AddDateTipActivity.this, "提交失败");
		}

		protected void handleData(JSONObject paramJSONObject, Map<String, Object> paramMap) throws JSONException {
			int retCode = paramJSONObject.getInt("code");
			if (retCode == ErrorCode.OK) {

				JSONArray jsonArray = new JSONArray();
				JSONObject jsonObject = paramJSONObject.getJSONObject("data");
				int id = jsonObject.getInt("id");
				jsonArray.put(jsonObject);
				databaseapi.updateRegardsTip(userInfoManager.id, jsonArray, 12);

				Common.tip(AddDateTipActivity.this, "提交成功");
				Intent intent = new Intent();
				intent.putExtra("id", id);
				setResult(RESULT_OK, intent);

				MobclickAgent.onEvent(AddDateTipActivity.this, UmengPage.datetip_add_success);
				myfinish();

			} else {
				Common.tip(AddDateTipActivity.this, ErrorCode.GetErrorMsg(retCode));
			}
		}

		protected String runTask(Map<String, Object> paramMap) {

			String dataString = cDate + " " + cTime;
			return nnSyncApi.PushRegardsTip(tid, title, dataString, settingString + "", desc);
		}
	}

	@Override
	public void onBackPressed() {
		myfinish();
	}
}
